﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace TurtleLib.Simulation
{
  public class DragComponent
  {
    private Point? _dragPoint;

    public event Action<Size> Drag;
    public event Action Captured;
    public event Action Released;

    public DragComponent()
    {
      _dragPoint = null;
    }

    public void SubscribeTo(Control control)
    {
      control.MouseUp += OnMouseUp;
      control.MouseDown += OnMouseDown;
      control.MouseMove += OnMouseMove;
    }

    public void SubscribeTo(IChildPanel childPanel)
    {
      childPanel.MouseUp += OnMouseUp;
      childPanel.MouseDown += OnMouseDown;
      childPanel.MouseMove += OnMouseMove;
    }

    public void ReleaseCurrentDrag()
    {
      Console.WriteLine("Released");

      _dragPoint = null;
      if (Released != null)
        Released();
    }

    protected void OnMouseDown(object sender, MouseEventArgs me)
    {
      if (me.Button == System.Windows.Forms.MouseButtons.Left)
      {
        _dragPoint = me.Location;

        if (Captured != null)
          Captured();
      }
    }

    protected void OnMouseUp(object sender, MouseEventArgs me)
    {
      ReleaseCurrentDrag();
    }

    protected void OnMouseMove(object sender, MouseEventArgs e)
    {
      if (_dragPoint.HasValue && Drag != null)
      {
        var dragValue = _dragPoint.Value;
        Drag(new Size(e.X - dragValue.X, e.Y - dragValue.Y));
      }
    }
  }
}
